import { defineStore } from "pinia";
import { ref } from "vue";
import { getUserInfo as fetchUserInfo } from "@/api/user";

export const useUserStore = defineStore("user", () => {
  // 状态
  const token = ref(localStorage.getItem("token") || "");
  const userInfo = ref({
    id: "",
    username: "",
    nickname: "",
    avatar: "",
    role: "",
    permissions: [],
  });

  // actions
  const setToken = (newToken) => {
    token.value = newToken;
    localStorage.setItem("token", newToken);
  };

  const clearToken = () => {
    token.value = "";
    localStorage.removeItem("token");
  };

  const setUserInfo = (info) => {
    userInfo.value = info;
    // 可以存储在localStorage中，但敏感信息应考虑安全问题
  };

  const logout = () => {
    clearToken();
    userInfo.value = {
      id: "",
      username: "",
      nickname: "",
      avatar: "",
      role: "",
      permissions: [],
    };
  };

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const res = await fetchUserInfo();
      if (res.code === 200 && res.data) {
        setUserInfo(res.data);
        return res.data;
      }
      throw new Error(res.message || "获取用户信息失败");
    } catch (error) {
      console.error("获取用户信息失败:", error);
      throw error;
    }
  };

  // 检查是否有指定权限
  const hasPermission = (permission) => {
    if (!userInfo.value.permissions) return false;
    // 如果是超级管理员
    if (userInfo.value.role === 'admin' || userInfo.value.permissions.includes('*')) {
      return true;
    }
    // 检查具体权限
    return userInfo.value.permissions.includes(permission);
  };

  return {
    token,
    userInfo,
    setToken,
    clearToken,
    setUserInfo,
    logout,
    getUserInfo,
    hasPermission,
  };
});
